package com.moco.launcher.fragment;

import java.util.ArrayList;
import java.util.List;

import com.moco.launcher.R;
import com.moco.launcher.activity.MainActivity;
import com.moco.launcher.bean.MOCO_CONSTANTS;
import com.moco.launcher.bean.MocoItemInfo;
import com.moco.launcher.bean.PickItemInfo;
import com.moco.launcher.listener.CloudListener;
import com.moco.launcher.listener.OnMusicCategorySelectedListener;
import com.moco.launcher.listener.OnStorySelectedListener;
import com.moco.launcher.listener.SelectStoryListCallback;
import com.oazon.common.util.RequestManager;
import com.moco.launcher.view.PickerView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.Toast;

public class StorytellingFragment extends BaseFragment implements
		SelectStoryListCallback {

	private static final String TAG = "StorytellingFlagment";

	private List<PickItemInfo> data = new ArrayList<PickItemInfo>();
	private List<MocoItemInfo> mCategory = new ArrayList<MocoItemInfo>();
	private PickerView mPickerView = null;
	private OnStorySelectedListener mOnStorySelectedListener = null;
	private int nLevel = 0;
	private StringBuilder mCurrentUrl = new StringBuilder();
	private View rootView = null;
	private ImageView exitImageView = null;
	private DisplayImageOptions options;
	private ImageView mSelector;
	private ImageView categoryBack;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ImageScaleType imageScaleType = ImageScaleType.EXACTLY_STRETCHED;
		options = new DisplayImageOptions.Builder().cacheInMemory(true)
				.cacheOnDisc(true).imageScaleType(imageScaleType)
				.considerExifParams(true).bitmapConfig(Bitmap.Config.RGB_565)
				.build();
	}

	@Override
	public void onAttach(Activity activity) {
		mOnStorySelectedListener = (OnStorySelectedListener) activity;
		MainActivity m = (MainActivity) activity;
		// m.registerGetStoryList(this);
		super.onAttach(activity);
	}

	private void getList(String url) {
		Log.d(TAG, "getList= " + url);
		RequestManager.sendRequest(this.getActivity(), url,
				new CloudListener() {
					@Override
					public void onResponse(String response) {
						Log.d(TAG, "response= " + response);
						RequestManager.parseJsonResponse(response, mCategory);
						notifyDataChanged();
					}

					@Override
					public void onError(int err, String msg) {
						Log.d(TAG, "err= " + msg);
					}
				});
	}

	private void notifyDataChanged() {
		data.clear();
		for (int i = 0; i < mCategory.size(); i++) {
			PickItemInfo item = new PickItemInfo();
			item.setText(mCategory.get(i).getTitle());
			item.setId(mCategory.get(i).getId());
			data.add(item);
		}

		mPickerView.setData(data);
		mPickerView.post(new Runnable() {
			@Override
			public void run() {
				mPickerView.invalidate();
			}
		});
		// TODO gavin displayItemInfo(mPickerView.getCurrentSelectId());
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		rootView = inflater.inflate(R.layout.storytellingchild_layout,
				container, false);
		
		categoryBack = (ImageView) rootView.findViewById(R.id.stc_category_back);
		ImageView limageview = (ImageView) rootView
				.findViewById(R.id.stc_category_left);
		limageview.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				prevFragment();
			}
		});

		ImageView rimageview = (ImageView) rootView
				.findViewById(R.id.stc_category_right);
		rimageview.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				nextFragment();
			}
		});

		ImageView stc_continue = (ImageView) rootView
				.findViewById(R.id.stc_continue_play);
		exitImageView = (ImageView) rootView.findViewById(R.id.stc_exit);
		stc_continue.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				MocoItemInfo info = getItemInfo(mPickerView
						.getCurrentSelectId());
				if (mOnStorySelectedListener != null) {
					mOnStorySelectedListener.onStoryContinue(info);
				}
			}

		});
		ImageView stc_replay = (ImageView) rootView
				.findViewById(R.id.stc_replay);
		stc_replay.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				MocoItemInfo info = getItemInfo(mPickerView
						.getCurrentSelectId());
				if (mOnStorySelectedListener != null) {
					mOnStorySelectedListener.onStoryReplay(info);
				}
			}
		});

		mSelector = (ImageView) rootView
				.findViewById(R.id.stc_category_selector);
		mPickerView = (PickerView) rootView
				.findViewById(R.id.stc_music_category_choice);
		mPickerView
				.setOnSelectListener(new com.moco.launcher.view.PickerView.onSelectListener() {
					@Override
					public boolean onRelayout(String selectId,
							com.moco.launcher.view.PickerView.UiParam param) {
						Log.d(TAG, "onSelected " + selectId);
						if (nLevel > 0) {
							exitImageView.setVisibility(View.VISIBLE);
						} else {
							exitImageView.setVisibility(View.GONE);
						}
						MocoItemInfo info = getItemInfo(selectId);
						if (info.getType().equals(
								MOCO_CONSTANTS.ITEM_TYPE.MEDIA)) {
							param.nMarginWidth = StorytellingFragment.this
									.getActivity()
									.getResources()
									.getDimension(
											R.dimen.picker_view_margin_width);
							rootView.findViewById(R.id.stc_continue_play)
									.setVisibility(View.VISIBLE);
							rootView.findViewById(R.id.stc_replay)
									.setVisibility(View.VISIBLE);
							return true;
						} else {
							rootView.findViewById(R.id.stc_continue_play)
									.setVisibility(View.GONE);
							rootView.findViewById(R.id.stc_replay)
									.setVisibility(View.GONE);
						}

						return false;
					}

					@Override
					public boolean onStop(String nSelectId) {
						// TODO gavin displayItemInfo(nSelectId);
						categoryBack.setImageResource(ids.get((int) (Math
								.random() * 4)));
						return true;
					}

					@Override
					public boolean onSelect(String nSelectId) {
						return false;
					}
				});

		mPickerView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Log.d(TAG, "ONCLICK.......");
				PickerView view = (PickerView) v;
				MocoItemInfo info = getItemInfo(view.getCurrentSelectId());
				if ((info != null)
						&& info.getType().equals(
								MOCO_CONSTANTS.ITEM_TYPE.CATEGORY)) {

					if (mCurrentUrl.length() == 0) {
						mCurrentUrl.append(MOCO_CONSTANTS.PROGRAM_URL);
					}

					nLevel++;
					mCurrentUrl.append("&l").append(nLevel).append("=")
							.append(info.getId());
					Log.d(TAG, "CURRENT url= " + mCurrentUrl.toString());
					getList(mCurrentUrl.toString());
				} else if ((info != null)
						&& info.getType().equals(MOCO_CONSTANTS.ITEM_TYPE.SONG)) {

				}
			}
		});

		exitImageView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (nLevel <= 0)
					return;
				String level = "&l" + nLevel;
				int nPos = mCurrentUrl.indexOf(level);
				mCurrentUrl.delete(nPos, mCurrentUrl.length());
				nLevel--;
				if (nLevel <= 0)
					nLevel = 0;
				getList(mCurrentUrl.toString());
			}
		});
		mCurrentUrl.delete(0, mCurrentUrl.length());
		getList(MOCO_CONSTANTS.PROGRAM_URL);
		return rootView;
	}

	public MocoItemInfo getItemInfo(String id) {
		for (MocoItemInfo info : mCategory) {
			if (info.getId() == id) {
				return info;
			}
		}
		return null;
	}

	@Override
	public void getStoryList(ArrayList<MocoItemInfo> list) {

	}

	public boolean displayItemInfo(String nSelectId) {
		MocoItemInfo info = getItemInfo(nSelectId);
		if (info == null)
			return false;
		ImageLoader.getInstance().displayImage(info.getPicture(), mSelector,
				options, new SimpleImageLoadingListener() {
					@Override
					public void onLoadingStarted(String imageUri, View view) {

					}

					@Override
					public void onLoadingFailed(String imageUri, View view,
							FailReason failReason) {
						String message = null;
						switch (failReason.getType()) {
						case IO_ERROR:
							message = "Input/Output error";
							break;
						case DECODING_ERROR:
							message = "Image can't be decoded";
							break;
						case NETWORK_DENIED:
							message = "Downloads are denied";
							break;
						case OUT_OF_MEMORY:
							message = "Out Of Memory error";
							break;
						case UNKNOWN:
							message = "Unknown error";
							break;
						}
						Toast.makeText(StorytellingFragment.this.getContext(),
								message, Toast.LENGTH_SHORT).show();
					}

					@Override
					public void onLoadingComplete(String imageUri, View view,
							Bitmap loadedImage) {

					}
				});

		return true;
	}
}
